package club.janna.jrpc.cluster.loadbalance;

import club.janna.jrpc.cluster.loadbalance.selector.Selector;
import club.janna.jrpc.rpc.Invoker;

/**
 * 负载均衡器抽象模板
 * @author Panbo.Guo
 */
public abstract class AbstractLoadBalancer implements LoadBalancer {

    private Invoker[] invokers;
    private Selector selector;

    /**
     * 构造选择器
     * @param invokers
     * @return
     */
    protected abstract Selector buildSelector(Invoker[] invokers);

    @Override
    public void init(Invoker[] invokers) {
        if(invokers == null || invokers.length == 0) {
            this.invokers = null;
            this.selector = null;
            return;
        }
        this.invokers = invokers;
        this.selector = buildSelector(invokers);
    }

    @Override
    public Invoker next() {
        if(selector == null || invokers == null)
            throw new RuntimeException("No service provider found!");
        return invokers[selector.next()];
    }
}
